package com.lb.shopguide.ui.fragment.guide.goods;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.LubanOptions;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.config.AppConfigManager;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.QiniuInfo;
import com.lb.shopguide.event.guide.TakePhotoErrorEvent;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.activity.ScanSmallActivity;
import com.lb.shopguide.ui.dialog.DialogSelectPic;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.lb.shopguide.util.lb.SelectPicUtil;
import com.qiniu.android.common.AutoZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.tencent.bugly.crashreport.CrashReport;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

/**
 * Created by kang on 2017/6/12.
 */

public class FragmentPublishGoods extends BaseCommonFragment implements TakePhoto.TakeResultListener, InvokeListener {

    private String barcode;
    private String picUrl;
    private String filePath;
    private String webUrl;
    private int mode;

    private BridgeWebView mWebView;
//    private NormalTitleBar ntb;

    private InvokeParam invokeParam;
    private TakePhoto takePhoto;
    private ProgressBar progressBar;

    private UploadManager uploadManager;
    private CallBackFunction picCallBackFunction;
    private CallBackFunction barcodeCallBackFunction;


    public static FragmentPublishGoods newInstance(String url, int mode) {
        FragmentPublishGoods fragmentPublishGoods = new FragmentPublishGoods();
        Bundle bundle = new Bundle();
        bundle.putString(AppConstant.WEB_URL, url);
        bundle.putInt(AppConstant.PUBLISH_TYPE, mode);
        fragmentPublishGoods.setArguments(bundle);
        return fragmentPublishGoods;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_publish_goods_webview;
    }

    @Override
    public void initData() {
        mUserConfigManager = UserConfigManager.getInstance(mContext);
        Configuration config = new Configuration.Builder().zone(AutoZone.autoZone).build();
        uploadManager = new UploadManager(config);
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.WEB_URL)) {
            webUrl = bundle.getString(AppConstant.WEB_URL);
        }
        if (bundle.containsKey(AppConstant.PUBLISH_TYPE)) {
            mode = bundle.getInt(AppConstant.PUBLISH_TYPE);
        }
        EventBus.getDefault().register(this);
    }

    @SuppressLint("JavascriptInterface")
    @Override
    public void initView() {
//        ntb = view.findViewById(R.id.ntb);
        mWebView = view.findViewById(R.id.webView);
//        rootLayout = view.findViewById(R.id.rlRoot);
        progressBar = view.findViewById(R.id.progress_bar);

//        if (mode == AppConstant.PUBLISH_TYPE_NEW) {
//            ntb.setTitleText("发布商品");
//        } else if (mode == AppConstant.PUBLISH_TYPE_EDIT) {
//            ntb.setTitleText("编辑商品");
//        }
//
//        ntb.setLeftImageSrc(R.drawable.iv_back);
//        ntb.setOnLeftImageListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                pop();
//            }
//        });
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setTextSize(WebSettings.TextSize.NORMAL);
        // 进度条控制
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (isVisible()) {
                    if (newProgress >= 100) {
                        progressBar.setVisibility(View.GONE);
                    } else {
                        progressBar.setVisibility(View.VISIBLE);
                    }
                    super.onProgressChanged(view, newProgress);
                }
            }

        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.setDefaultHandler(new DefaultHandler());

        mWebView.loadUrl(webUrl);
//        mWebView.loadUrl("http://www.baidu.com");

        mWebView.registerHandler("selectPicture", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                picCallBackFunction = function;
                SelectPicUtil.showDialogSelectPic("选择图片", mOnSelectPhotoListener, FragmentPublishGoods.this);
            }
        });

        mWebView.registerHandler("selectPictureNoCrop", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                picCallBackFunction = function;
                SelectPicUtil.showDialogSelectPic("选择图片", mOnSelectPhotoListener, FragmentPublishGoods.this, true);
            }
        });

        mWebView.registerHandler("getBarcode", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                barcodeCallBackFunction = function;
                Intent intent = new Intent(mContext, ScanSmallActivity.class);
                intent.putExtra(AppConstant.SCAN_MODE, AppConstant.SCAN_RETURN_BARCODE);
                startActivityForResult(intent, AppConstant.REQUEST_CODE_GET_BAR_CODE);
            }
        });
        mWebView.registerHandler("backToList", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                popTo(FragmentSelectGoods.class, false);
            }
        });
        mWebView.registerHandler("backToDetail", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
//                final FragmentGoodsDetail fragment = findFragment(FragmentGoodsDetail.class);
//                popTo(FragmentGoodsDetail.class, false, new Runnable() {
//                    @Override
//                    public void run() {
//                        fragment.onRefresh();
//                    }
//                });
                pop();
            }
        });
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) _mActivity).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    @Override
    public String getPageTag() {
        return FragmentPublishGoods.class.getName();
    }

//    public void gotoEdit(String id) {
//        if (mode == AppConstant.PUBLISH_TYPE_NEW) {
//            ntb.setTitleText("编辑商品");
//            if (AppConfigManager.getAppconfigManager(mContext).getDevMode() == AppConstant.KEY_RUN_MODE_FORMAL) {
//                mWebView.loadUrl("https://singlepage.storeer.com/v2/editGoods?" + "staffCode=" + mUserConfigManager.getUserId()
//                        + "&id=" + id + "&token=" + mUserConfigManager.getUserToken() + "&type=android");
//            } else {
//                mWebView.loadUrl("http://192.168.1.102:8088/v2/editGoods?" + "staffCode=" + mUserConfigManager.getUserId()
//                        + "&id=" + id + "&token=" + mUserConfigManager.getUserToken() + "&type=android");
//            }
//
//        }
//    }


    private CropOptions getCropOptions() {
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setAspectX(3).setAspectY(4);
        builder.setWithOwnCrop(true);
        return builder.create();
    }

    private void configCompress(TakePhoto takePhoto) {
//        int height = 480;
//        int width = 360;
        int height = ConvertUtils.dp2px(ScreenUtils.getScreenHeight());
        int width = ConvertUtils.dp2px(ScreenUtils.getScreenWidth());
        int maxSize = 409600;
        LubanOptions option = new LubanOptions.Builder()
                .setMaxHeight(height)
                .setMaxWidth(width)
                .setMaxSize(maxSize)
                .create();
        CompressConfig config = CompressConfig.ofLuban(option);
        config.enableReserveRaw(true);
        takePhoto.onEnableCompress(config, true);
    }

    private void configTakePhotoOption(TakePhoto takePhoto) {
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(true);
        builder.setCorrectImage(true);
        takePhoto.setTakePhotoOptions(builder.create());
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            getTakePhoto().onActivityResult(requestCode, resultCode, data);
            if (requestCode == AppConstant.REQUEST_CODE_GET_BAR_CODE) {
                barcode = data.getStringExtra(AppConstant.BARCODE);
                barcodeCallBackFunction.onCallBack(barcode);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(_mActivity, type, invokeParam, this);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }


    private void sendRequestGetQiniuToken() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    QiniuInfo qiniuInfo = (QiniuInfo) JsonUtil.getObject(response.getReturnContent(), QiniuInfo.class);
                    String token = qiniuInfo.getUploadToken();
                    final String domain = qiniuInfo.getPathUrl();//http://static.storeer.com/appuser/headpic/
                    String key = AppConstant.QINIU_PATH + System.currentTimeMillis() + "_android_" + BizUtil.getRandomName(3) + AppConstant.PNG;
                    uploadManager.put(filePath, key, token, new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject response) {
                            try {
                                CrashReport.putUserData(mContext, "response", response.toString());
                                CrashReport.putUserData(mContext, "picKey", key);
                                picUrl = domain + "/" + response.getString("key");
                                LogUtils.d("picUrl======" + picUrl);
                                picCallBackFunction.onCallBack(picUrl);
//                                    EventBus.getDefault().post(new GetPhotoEvent(picUrl));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, null);
                } else {
                    ToastUtils.showShort("暂时不能上传头像");
                }
            }
        };
        ApiMethodGuide.getQiniuToken(new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }


    private DialogSelectPic.OnSelectPhotoListener mOnSelectPhotoListener = new DialogSelectPic.OnSelectPhotoListener() {
        @Override
        public void onTakePhoto(int id, boolean ifCrop) {
            File file = new File(AppConfigManager.DIR_IMAGE + System.currentTimeMillis() + AppConstant.JPG); // 存放路径
            if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
            Uri imageUri = Uri.fromFile(file);
            configCompress(takePhoto);
            configTakePhotoOption(takePhoto);
            switch (id) {
                case R.id.rl_profile_take_photo:
                    if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {//权限不被允许
                        if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
                            ToastUtils.showLong("请先开启app拍照权限...");
                        } else {
                            requestPermissions(new String[]{Manifest.permission.CAMERA}, AppConstant.REQUEST_CODE_CAMERA_PERMISSION);//请求权限
                        }
                    } else {//权限允许
                        if (ifCrop) {
                            takePhoto.onPickFromCapture(imageUri);
                        } else {
                            takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions());
                        }
                    }
                    break;
                case R.id.rl_profile_local_photo:
                    if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {//权限不被允许
                        if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                            ToastUtils.showLong("请先开启app存储权限...");
                        } else {
                            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, AppConstant.REQUEST_CODE_LOCAL_PICTURE);//请求权限
                        }
                    } else {//权限允许
                        if (ifCrop) {
                            takePhoto.onPickFromGallery();
                        } else {
                            takePhoto.onPickFromGalleryWithCrop(imageUri, getCropOptions());
                        }
                    }
                    break;
            }
        }
    };

    @Override
    public void takeSuccess(TResult result) {
        filePath = result.getImage().getCompressPath();
        if (!TextUtils.isEmpty(filePath)) {
            sendRequestGetQiniuToken();
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
        EventBus.getDefault().post(new TakePhotoErrorEvent(msg));
    }

    @Override
    public void takeCancel() {
        ToastUtils.showShort("取消");
    }


    @Subscribe
    public void onTakePhotoError(TakePhotoErrorEvent event) {
        ToastUtils.showLong(event.getMsg());
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        rootLayout.removeView(mWebView);
//        mWebView.destroy();
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
